<template>
  <div class="container">
    <el-row class="tags-container">
      <el-card class="box-card">
        <el-row>
                <!-- 面包屑 -->
      <el-breadcrumb
        v-if="true"
        separator-class="el-icon-arrow-right"
        style="margin-bottom: 20px"
      >
        <el-breadcrumb-item>学科管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ subjectName }}</el-breadcrumb-item>
        <el-breadcrumb-item>标签管理</el-breadcrumb-item>
      </el-breadcrumb>
          <el-col :span="14">
            <el-form :inline="true" :model="formInline" ref="searchFrom">
              <el-form-item label="标签名称" label-width="80px">
                <el-input v-model="formInline.tagName"></el-input>
              </el-form-item>
              <el-form-item label-width="80px" label="状态" >
                <el-select v-model="formInline.state" >
                  <el-option
                    v-for="item in Status"
                    :key="item.index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                  <!-- @click.native="changState(item.value)" -->
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="clickSearch">清除</el-button>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
              </el-form-item>
            </el-form>
          </el-col>
            <el-col :span="7">
              <el-link
            type="primary"
            v-if="show"
            icon="el-icon-back"
            :underline="false"
            @click="$router.push({ path: 'list' })"
            style="margin-left: 280px;margin-top:10px"
            >返回学科</el-link
          >
            </el-col>
          <el-col :span="3" style="text-align: right">
            <el-button type="success" icon="el-icon-edit" @click="hAdd()"
              >新增标签</el-button
            >
          </el-col>

          <el-alert
            :title="`数据一共${total}条`"
            :closable="false"
            type="info"
            show-icon
          >
          </el-alert>
        </el-row>
        <el-table
          :header-cell-style="{ background: '#fafafa', color: '#909399' }"
          :data="list"
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科">
          </el-table-column>
          <el-table-column prop="tagName" label="标签名称"> </el-table-column>
          <el-table-column prop="username" label="创建者"> </el-table-column>
          <el-table-column prop="addDate" label="创建日期"> </el-table-column>
          <el-table-column prop="state" label="状态">
            <template #default="{ row }">
              <!-- {{NowState(row.state)}} -->
              {{ row.state === 1 ? "已启用" : "已禁用" }}
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作">
            <template #default="{ row }">
              <el-button @click="handleClick(row)" type="text" size="small"
                ><span v-if="row.state == 0">启用</span>
                <span v-else>禁用</span>
              </el-button>
              <el-button
                type="text"
                size="small"
                :disabled="row.state === 1"
                @click="hEdit(row)"
                >修改</el-button
              >
              <el-button
                @click="hDel(row.id)"
                type="text"
                size="small"
                :disabled="row.state === 1"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          style="margin-top: 20px; text-align: right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="obj.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="obj.pagesize"
          layout="prev, pager, next,sizes, jumper"
          :total="total"
        >
        </el-pagination>
      </el-card>
    </el-row>

  <el-dialog :title="isEdit?'编辑':'添加'" :visible.sync="showDialog" width="30%"  @close="restForm">
  <el-form :model="form"  ref="ruleForm">
     <el-form-item label="所属学科"   v-if="!show" >
      <el-select
       v-model="form.subjectName"
      placeholder="活动名称"
      style="width: 80%"
   >
        <el-option
       v-for="item in list"
        :key="item.id"
        :label="item.subjectName"
        :value="item.id"
        @click.native="changeItem(item.subjectID)"
         />
      </el-select>
    </el-form-item>
    <el-form-item label="活动名称" >
      <el-input v-model="form.tagName" autocomplete="off" style="width: 80%"></el-input>
    </el-form-item>
  </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button>取 消</el-button>
        <el-button type="primary" @click="hSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, changeState, add, update, remove } from '@/api/hmmm/tags.js'
// 导入枚举文件
import { status } from '@/api/hmmm/constants.js'
import { simple } from '@/api/hmmm/subjects.js'
// console.log(BaseApi.status)
// const status = {}
// BaseApi.status.forEach(item => {
//   status[item.id] = item.value
// })

export default {
  data () {
    return {
      search: [],
      Status: status,
      showDialog: false,
      isEdit: false,
      total: 0, // 总条数
      id: 0,
      list: [],
      // subjectID: '',
      // curId: '',
      formInline: {
        tagName: '',
        state: null
      },
      form: {
        subjectName: '',
        tagName: '',
        subjectID: ''
      },
      obj: {
        page: 1,
        pagesize: 10,
        tagName: '',
        state: null
      },
      show: false,
      subjectName: this.$route.query.name,
      subjectID: this.$route.query.id,
      subjectData: {}
    }
  },
  created () {
    this.loadList()
    this.getSubjectList()
    this.getPath()
  },

  methods: {
    // 添加
    async doAdd () {
      if (this.subjectName !== undefined) {
        const res = await add({
          subjectID: +this.subjectID,
          tagName: this.form.tagName
        })
        if (res.status !== 200) return this.$message.error('添加失败')
        this.$message.success('添加成功')
      } else {
        const res = await add(this.form)
        if (res.status !== 200) return this.$message.error('添加失败')
        this.$message.success('添加成功')
      }
      this.loadList()
      this.showDialog = false
    },
    async getSubjectList () {
      const res = await simple({ page: 1, pagesize: 999 })
      this.subjectData = res.data
      // console.log(res, '简单列表')
    },
    getPath () {
      if (this.subjectName !== undefined) {
        this.show = true
      } else {
        this.show = false
      }
      this.loadList()
    },
    async loadList () {
      try {
        const res = await list(this.obj)
        if (this.show) {
          const newRes = await list({ page: 1, pagesize: res.data.counts })
          const arr = newRes.data.items
          const oldArr = []
          const newArr = arr.filter((item) => {
            if (item.subjectName === this.subjectName) {
              return oldArr.push(item)
            }
          })
          newArr.forEach(item => {
            item.addDate = this.dayjs(item.addDate).format('YYYY.MM.DD')
          })
          this.list = newArr
          this.total = newArr.length
        } else {
          this.list = res.data.items
          this.total = res.data.counts
        }
        // 保存数据
      } catch (err) {
        console.log('err', err)
      }
    },
    // 搜索
    async onSubmit () {
      this.obj = this.formInline
      this.loadList()
      // console.log(this.obj, 'this.obj')
    },
    // 重置清空
    clickSearch () {
      this.$refs.searchFrom.resetFields()
      this.formInline = {
        tagName: '',
        state: ''
      }
      // this.loadList()
      // this.$router.back()
    },
    // changState (state) {
    //   console.log(state)
    //   this.obj.state = state
    // },
    hDel (id) {
      console.log(id, '删除id')
      this.$confirm('你确定要删除吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await remove({ id: id })
          console.log(res, '删除')
          // if (res.status !== 200) return this.$message.error('删除失败')
          // this.$message.success('删除成功')
          this.loadList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 重置表单和数据
    restForm () {
      this.$refs.ruleForm.resetFields()
      this.form = {
        subjectName: '',
        tagName: '',
        subjectID: ''
      }
    },
    // 获取选中的名称对应的id
    changeItem (id) {
      // console.log(id)
      this.form.subjectID = id
    },
    hSubmit () {
      this.isEdit ? this.doEdit() : this.doAdd()
    },
    // 编辑
    async doEdit () {
      try {
        const res = await update({ ...this.form })
        console.log('update', res)
        if (res.status !== 200) return this.$message.error('编辑失败')
        this.$message.success('编辑成功')
        this.loadList()
        this.showDialog = false
        // 保存数据
      } catch (err) {
        console.log('update', err)
      }
    },
    hAdd () {
      this.isEdit = false
      this.showDialog = true
    },
    async hEdit (row) {
      this.isEdit = true
      this.showDialog = true
      // const res = await detail(row)
      this.form = { ...row }
      console.log(row, 'row')
    },
    // 状态切换
    async handleClick (row) {
      const res = await changeState({
        id: row.id,
        state: row.state === 1 ? 0 : 1
      })
      this.loadList()
      console.log(res, '状态')
    },
    // NowState (id) {
    //   console.log(id)
    //   return status[id] || '未知'
    // },

    handleSizeChange (val) {
      this.obj.pagesize = val
      this.obj.page = 1
      this.loadList()
    },
    handleCurrentChange (val) {
      this.obj.page = val
      this.loadList()
    }
  }
}
</script>

<style lang="scss" scoped>
// .box {
//   padding: 10px;
// }
.tags-container {
  padding: 10px;
}
  .box-card {
    width: 100%;
  }
  ::v-deep.el-input__inner {
      height: 32px;
      line-height: 32px;
      font-size: 12px;
    }
 .el-button--medium {
      padding: 9px 15px;
      font-size: 12px;
    }
    .el-alert {
      margin-bottom: 15px;
    }
</style>
